using System.Runtime.InteropServices;

using Game.Input;
using Game.Output;

namespace Game.Utils
{
	public static class CTimer
	{
		[System.Security.SuppressUnmanagedCodeSecurity]
		[DllImport("kernel32")]
		private static extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);
		
		[System.Security.SuppressUnmanagedCodeSecurity]
		[DllImport("kernel32")]
		private static extern bool QueryPerformanceCounter(ref long PerformanceCount);
		
		private static bool m_isAvailable		= false;
		private static long m_ticksPerSecond	= 0;
		private static long m_lastFrame			= 0;
		private static long m_currentFrame		= 0;
		private static long m_elapsedTime		= 0;
		
		public static void Initialize()
		{
			CConsole.ReportClassInit(System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name);
			
			m_isAvailable = QueryPerformanceFrequency(ref m_ticksPerSecond);
			
			if (!m_isAvailable)
				return;
			
			QueryPerformanceCounter(ref m_currentFrame);
		}
		
		public static void Update()
		{
			m_lastFrame = m_currentFrame;
			
			QueryPerformanceCounter(ref m_currentFrame);
			
			m_elapsedTime = m_currentFrame - m_lastFrame;
		}
		
		#region properties
		//****************
		
		public static bool IsAvailable
		{
			get { return m_isAvailable; }
		}
		
		public static float ElapsedTimeInMS
		{
			get {
				return ((float)m_elapsedTime / (float)m_ticksPerSecond) / 1000.0f;
			}
		}
		
		public static float ElapsedTimeInSeconds
		{
			get {
				return (float)m_elapsedTime / m_ticksPerSecond;
			}
		}
		
		public static long Time
		{
			get
			{
				long tmpTime = 0;
				QueryPerformanceCounter(ref tmpTime);
				
				return tmpTime / m_ticksPerSecond;
			}
		}
		
		#endregion properties
	}
}
